package com.data.permission.transf;

import org.apache.commons.pool2.BaseKeyedPooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TSocket;

/**
 * @包名称 com.thrift.distributed.process
 * @类描述 <pre></pre>
 * @作者 zhangbo
 * @创建时间 2019/9/19
 * @版本 1.00
 * @修改记录 <pre>
 *     版本           修改人         修改日期         修改内容描述
 *     -----------------------------------------------------------
 *     1.00           Lenovo        2019/9/19
 *     -----------------------------------------------------------
 * </pre>
 */
public class ClientFactory extends BaseKeyedPooledObjectFactory<ServiceInfo,TProtocol> {

    @Override
    public TProtocol create(ServiceInfo serviceInfo) throws Exception {
        TSocket socket = new TSocket(serviceInfo.getServiceHost(),serviceInfo.getServicePort(),serviceInfo.getTimeout());
        TFramedTransport transport = new TFramedTransport(socket);
        TProtocol protocol = new TCompactProtocol(transport);
        transport.open();
        return protocol;
    }

    @Override
    public PooledObject<TProtocol> wrap(TProtocol tProtocol) {
        return new DefaultPooledObject<>(tProtocol);
    }

    /**
     * 验证对象是否可用
     * @param key
     * @param p
     * @return
     */
    @Override
    public boolean validateObject(ServiceInfo key, PooledObject<TProtocol> p) {
        DataPermissionsService.Client client = new DataPermissionsService.Client(p.getObject());
        try {
            client.ping();
        } catch (TException e) {
            return false;
        }
        return true;
    }

    /**
     * 销毁对象
     * @param key
     * @param p
     * @throws Exception
     */
    @Override
    public void destroyObject(ServiceInfo key, PooledObject<TProtocol> p) throws Exception {
        p.getObject().getTransport().close();
    }
}
